package com.power.web.action.doctor;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.power.Constants;
import com.power.model.doctor.TiDoctors;
import com.power.model.user.TsSysuser;
import com.power.services.doctors.TiDoctorsService;
import com.power.util.CharacterUtil;
import com.power.util.DateJsonValueProcessor;
import com.power.util.DateTimeUtil;
import com.power.util.FileUtil;
import com.power.util.PingYinUtil;
import com.power.util.RequestUtil;
import com.power.util.XmlUtil;
import com.power.web.action.base.AbstractBaseAction;

public class TiDoctorsAction extends AbstractBaseAction {

	@Autowired
	@Qualifier("tiDoctorsService")
	private TiDoctorsService tiDoctorsService;
	private File imgFile;
	private String imgFileFileName;
	private TiDoctors doctors;
	private String jsonString;
	private int flag;

	@SuppressWarnings("unchecked")
	public String buildJSONString() {
		try {
			int start = this.start;
			int limit = this.limit;
			if (limit == 0)
				limit = 20;
			String realName = CharacterUtil.encode(RequestUtil.getParam(
					request, "realName", ""));
			Integer hid = RequestUtil.getParam(request, "hid", -1);
			Integer did = RequestUtil.getParam(request, "did", -1);
			Integer gid = RequestUtil.getParam(request, "gid", -1);
			Map<String, Object> map = this.tiDoctorsService.findAll(realName,
					start, limit, hid, did, gid);
			List<TiDoctors> list = (List<TiDoctors>) map.get("data");
			int count = new Integer(map.get("count").toString());
			StringBuffer _JSONStr = null;
			String callback = this.callback;
			_JSONStr = new StringBuffer();
			_JSONStr.append(callback).append("({\"total\":").append(count)
					.append(",\"results\":");
			JsonConfig cfg = new JsonConfig();
			cfg.registerJsonValueProcessor("inputDate",
					new DateJsonValueProcessor("yyyy-MM-dd kk:mm:ss"));
			cfg.registerJsonValueProcessor(java.util.Date.class,
					new DateJsonValueProcessor("yyyy-MM-dd"));
			cfg.registerJsonValueProcessor(java.sql.Date.class,
					new DateJsonValueProcessor("yyyy-MM-dd"));
			JSONArray jsonObject = JSONArray.fromObject(list, cfg);
			_JSONStr.append(jsonObject.toString());
			_JSONStr.append("})");
			jsonString = _JSONStr.toString();
		} catch (Exception e) {
			log.error("加载医生信息列表出错", e);
			this.jsonString = "[]";
		}
		return Constants.JSONSTRING_RESULT_NAME;
	}

	public String delete() throws Exception {
		String id = RequestUtil.getParam(this.request, "deleteID", "");
		String[] ids = id.split("_");
		try {
			this.response.setCharacterEncoding("UTF-8");
			for (int i = 0; i < ids.length; i++) {
				TiDoctors doctors = this.tiDoctorsService.read(new Integer(
						ids[i]));
				this.tiDoctorsService.delete(doctors);
			}
			this.response.getWriter().print("{success:true,msg:'删除成功!'}");
		} catch (Exception e) {
			log.error("输出JSON数据错误！", e);
			this.response.getWriter().print("{failure:true,msg:'删除失败!'}");
		}
		return null;
	}

	public String saveOrUpdate() {
		this.response.reset();
		this.response.setCharacterEncoding("UTF-8");
		try {
			if (null != doctors) {
				TsSysuser user = (TsSysuser) this.session
						.get(Constants.USERINFO_KEY);
				doctors.setInputDate(DateTimeUtil.getCurrentDateTime());
				doctors.setInputMan(user.getUsername());
				doctors.setInputManId(user.getId());
				tiDoctorsService.saveOrUpdate(doctors);
			}
			this.response.getWriter().print("{success:true,msg:'保存成功!'}");
		} catch (Exception e) {
			log.error("小组信息保存失败", e);
			try {
				this.response.getWriter().print("{success:false,msg:'保存失败!'}");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public String save() {
		this.response.reset();
		this.response.setCharacterEncoding("UTF-8");
		if (null != doctors) {
			if (null != imgFile) {
				String basePath = request.getSession().getServletContext()
						.getRealPath("/");
				String compressPath = XmlUtil.getValue("imgPath", "sysConfig")
						+ "/";
				String fileName = "";
				fileName = new Date().getTime()
						+ imgFileFileName.substring(imgFileFileName
								.lastIndexOf("."));
				if (FileUtil.doUpFile(basePath + compressPath + fileName,
						imgFile)) {
					doctors.setImgsrc(compressPath + fileName);
				}
			}
			TsSysuser user = (TsSysuser) this.session
					.get(Constants.USERINFO_KEY);
			doctors.setInputDate(DateTimeUtil.getCurrentDateTime());
			doctors.setInputMan(user.getUsername());
			doctors.setInputManId(user.getId());
			doctors.setFullChar(PingYinUtil.getPingYin(doctors.getRealName(),
					1, 1));
			doctors.setFirstChar(PingYinUtil.getPingYin(doctors.getRealName(),
					2, 1).substring(0, 1));
		}
		try {
			tiDoctorsService.saveOrUpdate(doctors);
			request.setAttribute("ifsuccess", "保存成功!");
		} catch (RuntimeException e) {
			request.setAttribute("ifsuccess", "保存失败!");
			e.printStackTrace();
		}
		return "ifsuccess";
	}

	public String showPage() {
		Integer hid = RequestUtil.getParam(request, "hid", 0);
		Integer did = RequestUtil.getParam(request, "did", 0);
		Integer gid = RequestUtil.getParam(request, "gid", 0);
		Integer id = RequestUtil.getParam(request, "id", 0);
		try {
			if (id == 0) {
				doctors = new TiDoctors();
				doctors.setHid(hid);
				doctors.setDid(did);
				doctors.setGid(gid);
			} else {
				doctors = tiDoctorsService.read(id);
			}
		} catch (Exception e) {
			log.error("获取数据错误");
			e.printStackTrace();
		}
		return "showPage";
	}

	public String execute() {
		return null;
	}

	public String getJsonString() {
		return jsonString;
	}

	public void setJsonString(String jsonString) {
		this.jsonString = jsonString;
	}

	public TiDoctors getdoctors() {
		return doctors;
	}

	public void setdoctors(TiDoctors doctors) {
		this.doctors = doctors;
	}

	public int getFlag() {
		return flag;
	}

	public void setFlag(int flag) {
		this.flag = flag;
	}

	public File getImgFile() {
		return imgFile;
	}

	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	public String getImgFileFileName() {
		return imgFileFileName;
	}

	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}

	public TiDoctors getDoctors() {
		return doctors;
	}

	public void setDoctors(TiDoctors doctors) {
		this.doctors = doctors;
	}

}